<template>
  <div>
    <div style="margin-bottom: 10px; font-size: 14px; font-weight: 250; margin-left: 10px">
      <el-icon><Memo /></el-icon>
      选修课程
    </div>
    <el-card style>
      <div style="display: flex">
        <el-input placeholder="请输入课程名称" v-model="data.courseName" style="width: 300px; margin-left: 700px;"  prefix-icon="Search"/>
        <el-input placeholder="请输入教师姓名" v-model="data.teacherName" style="width: 300px; margin: 0px 20px 0px 20px" prefix-icon="Search"/>
        <el-button type="primary" size="large" @click="load">搜索</el-button>
      </div>
      <el-table :data="data.tableData" stripe style="width: 100%">
        <el-table-column prop="courseId" label="课程ID" />
        <el-table-column prop="courseName" label="课程名" />
        <el-table-column prop="teacherName" label="教师" />
        <el-table-column prop="credit" label="学分" />
        <el-table-column label="上课时间">
          <template #default="scope">
            {{ formatTimeDisplay(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="selectCount" label="已选人数" />
        <el-table-column prop="maxSize" label="最大容量" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="chooseCourse(scope.row)" type="success" icon="Check" circle />
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-pagination layout="prev, pager, next" :total="data.tableData.length" :page-size="10" />
      </div>
    </el-card>
  </div>
</template>

<script setup>

import {reactive} from "vue";
import request from "@/utils/request.js";
import {formatCourseTime} from "@/utils/timeFormatter";
import {ElMessage} from "element-plus";

const data = reactive({
  tableData: [],
  courseName: "",
  teacherName: "",
  form: {},
})

const student = JSON.parse(localStorage.getItem("student"))

const load = () => {
  request.get("student/selectAllCourse", {
    params: {
      courseName: data.courseName || '',
      teacherName: data.teacherName || '',
      studentId: student.id,
    }}).then(res => {
    data.tableData = res.data
  })
}

load()

const formatTimeDisplay = (timeStr) => {
  return formatCourseTime(timeStr);
};

const chooseCourse = (row) => {
  data.form.courseId = row.id
  data.form.studentId = student.id
  request.post("student/chooseCourse", data.form).then(res => {
    if (res.code === "200") {
      ElMessage.success("选课成功")
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
</script>